/**
 * @Author: jipeng.Li
 * @Date: 2021-02-24 08:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-05-08 13:08:21
 * @Description: 油卡详情
 */
import React, { Component } from 'react';
import {
  Linking,
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
import {
  fontColorBlack,
  fontColorCoffee,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  screenHeight
} from '@/styles';
import { msg, AsyncStorage, cache } from '@/common';
import oil from '@/api/oil';
import QRCode from 'react-native-qrcode-svg';
import user from '@/api/user';
import EntityOilCard from './components/entity-oil-card';
import FictitiousOilCard from './components/fictitious-oil-card';
import FictitiousOilCardDetail from './components/fictitious-oil-card-detail';

export default class OliCardDetails extends Component {
  oilCardBtn = {
    // 虚拟油卡
    0: [
      { id: 0, text: '交易记录', routerName: 'OliCardTransactionsRecord' },
      { id: 1, text: '共享油卡', routerName: 'OliCardShareRecord' },
      // {id: 2, text: '申请拨油', routerName: 'PumpOil'},
    ],
    // 实体油卡
    1: [
      { id: 0, text: '申请拨油', routerName: 'PumpOil' },
    ],
    // 挂账卡
    2: [
      { id: 0, text: '核销记录', routerName: 'OliCardTransactionsRecord' },
    ]
  }

  qrCodeCount = null;

  timer = null;

  constructor(props) {
    super(props);
    this.state = {
      serviceNumber: '', // 客服电话
      qrCodeCountDown: 59,
      qrCode: '', // 二维码字符串
      pumpOilNo: '', // 核销码 用于轮询请求是否核销成功
      oilCardType: 0, // 油卡类型 0 虚拟 1 实体 2 挂账
      userType: '', // 用户类型 1 车主 2 司机,
      cardData: { empowerEndTime: '' }, // 油卡数据
      isWriteOff: false,
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { oilCardType, cardData } = params;
    this.getConfigValue();
    // 根据路由参数判断油卡类型 oilCardType： 1：实体 默认用户类型 1, 只有车主才有实体油卡 | 0： 虚拟 请求油卡虚拟油卡详情，根据详情赋值用户类型和油卡数据
    this.setState({ cardData, oilCardType }, () => this.entranceMain());
    msg.on('setUpQrCodeInterval', () => {
      this.setState({ qrCodeCountDown: 59 }, () => {
        this.setUpQrCodeInterval(true);
      });
    });
  }

  componentWillUnmount() {
    this.setUpQrCodeInterval(false);
    msg.off('setUpQrCodeInterval');
  }

  render() {
    const { serviceNumber, } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        {this.renderOilDetailsView()}
        <TouchableOpacity
          onPress={this.callServicePhone}
          style={{ alignItems: 'center', marginBottom: px2dp(20) }}
        >
          <Text>
            客服电话：
            {serviceNumber}
          </Text>
        </TouchableOpacity>
      </SafeAreaView>
    );
  }

  // 虚拟油卡视图
  renderOilDetailsView = () => {
    const { userType, qrCodeCountDown, qrCode, cardData, isWriteOff } = this.state;
    const { enterpriseStatus, status } = cardData;
    return (
      <View style={styles.detailsContainer}>
        <View style={styles.oilCardContainer}>
          <FictitiousOilCardDetail
            renderBottomContent={this.getOilCarTabData()}
            btnClick={() => this.routerJump()}
            {...this.convertCardData()}
          />
        </View>
        {/* 判断油卡状态与商户状态是否可用 */}
        {(enterpriseStatus === 'N' || status === 'N') || (
          <>
            <View style={styles.detailsDataContainer}>
              {/* 区分车主用油还是司机用油 */}
              <View style={styles.detailsHeadTitle}>
                {(userType && userType === 1) ? (
                  <Text style={{ color: fontColorBlack }}>车主用油</Text>
                ) : (
                  <View style={styles.detailsHeadTitleDriverContainer}>
                    <Text
                      style={{ fontSize: px2dp(28), flex: 1 }}
                      numberOfLines={1}
                      ellipsizeMode='middle'
                    >
                      <Text style={{ color: '#999793' }}>司机：</Text>
                      <Text style={{ color: fontColorBlack }}>
                        {`${this.convertCardData().driverName} ${(this.convertCardData().driverMobile)}`}
                      </Text>
                    </Text>
                    <Text style={{ fontSize: px2dp(28) }} numberOfLines={1}>
                      <Text style={{ color: '#999793' }}>车牌号：</Text>
                      <Text style={{ color: fontColorBlack }}>
                        {`${this.convertCardData().carNo}`}
                      </Text>
                    </Text>
                  </View>
                )}
              </View>
              {/* 是否请求到了二维码数据 */}
              {(qrCode !== '') && (
                <View style={styles.qrCodeContainer}>
                  <QRCode
                    value={qrCode}
                    logoBorderRadius={1}
                    color='#191919'
                    backgroundColor='#ffffff'
                    logoSize={30}
                    size={screenHeight / 5}
                  />
                  <Text style={{ fontSize: px2dp(28), marginTop: px2dp(20) }}>
                    {isWriteOff ? (
                      <Text style={{ color: '#999793' }}>正在核销中... </Text>
                    ) : (
                      <>
                        <Text style={{ color: '#999793' }}>剩余刷新时间 </Text>
                        <Text style={{ color: fontColorCoffee }}>{` ${qrCodeCountDown}s`}</Text>
                      </>
                    )}
                  </Text>
                </View>
              )}
            </View>
          </>
        )}
      </View>
    );
  }

  entranceMain = () => {
    const { oilCardType, cardData } = this.state;
    if (oilCardType === 0) { // 虚拟油卡
      this.getFictitiousCardById();
    }
    if (oilCardType === 1) { // 实体油卡
      this.setState({ userType: 1 });
    }
    if (oilCardType === 2) { // 挂账卡
      let newCardData = {};
      Object.assign(newCardData, cardData, { accountCarownerId: cardData.id });
      this.setState({ userType: 2, cardData: newCardData });
      this.getFictitiousCardQrCode();
    }
  }

  // 获取油卡tab按钮数据
  getOilCarTabData = () => {
    const { userType, oilCardType, cardData } = this.state;
    const { enterpriseStatus, status } = cardData;
    // 司机
    if (userType === 2) {
      if (cardData.isHangAccount) {
        return this.oilCardBtn[oilCardType];
      }
      return [];
    }
    // 若是车主 但是商户状态或油卡状态被禁用 只能查看交易记录
    if (userType === 1 && (enterpriseStatus === 'N' || status === 'N')) {
      return [this.oilCardBtn[oilCardType][0]];
    }
    return this.oilCardBtn[oilCardType];
  }

  // 创建虚拟油卡或实体油卡数据对象
  convertCardData = () => {
    const { cardData, oilCardType } = this.state;
    if (oilCardType === 1) { // 实体油卡
      return {
        owner: cardData.name || '',
        companyType: cardData.supplierName || '',
        cardNumber: cardData.oilcardNo || ''
      };
    }
    if (oilCardType === 0) { // 虚拟油卡
      return {
        balance: cardData.nowAmount || cardData.total || '', // 余额
        companyType: cardData.leaglName || '', // 法人名称
        companyName: cardData.allianceName || '', // 商户名称
        owner: cardData.caronwerCustName || '', // 所有人
        driverName: cardData.driverName || '', // 司机名字
        driverMobile: cardData.driverMobile || '', // 司机电话
        carNo: cardData.carNo || '', // 车牌号
      };
    }

    if (oilCardType === 2) { // 挂账卡
      return {
        owner: cardData.carownerName || '',
        companyType: cardData.legalCustName || '', // 法人名称
        companyName: cardData.allianceName || '', // 商户名称
        driverName: cardData.driverName || '', // 司机名字
        driverMobile: cardData.driverMobile || '', // 司机电话
        carNo: cardData.carNo || '', // 车牌号
        isHangAccount: cardData.isHangAccount // 挂账卡
      };
    }
  }

  // 油卡tab点击
  routerJump = () => {
    const { cardData, oilCardType } = this.state;
    msg.emit('router: goToNext', {
      routeName: 'OliCardTransactionsRecord',
      cardData,
      cardType: oilCardType,
    });
  }

  // 刷新二维码
  refreshQrCode = () => {
    if (this.qrCodeCount) {
      clearInterval(this.qrCodeCount);
      this.qrCodeCount = null;
    }
    this.qrCodeCount = setInterval(() => {
      const { qrCodeCountDown } = this.state;
      let time = qrCodeCountDown;
      if (time) {
        this.setState({ qrCodeCountDown: --time });
        return;
      }
      clearInterval(this.qrCodeCount);
      this.qrCodeCount = null;
      this.setState({ qrCodeCountDown: 59, qrCode: '' }, () => {
        this.getFictitiousCardQrCode();
      });
    }, 1000);
  }

  // 轮询结果
  pollingResult = (pollingFun) => {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.timer = setTimeout(pollingFun, 2000);
  }

  // 开启或关闭二维码请求刷新和核销结果轮询 true 开启 | false 关闭
  setUpQrCodeInterval = (flag) => {
    if (flag) {
      this.getFictitiousCardQrCode();
    } else {
      clearInterval(this.qrCodeCount);
      this.qrCodeCount = null;
      clearTimeout(this.timer);
      this.timer = null;
    }
  }

  // 拨打电话
  callServicePhone = () => {
    const { serviceNumber } = this.state;
    const url = `tel:${serviceNumber}`;
    Linking.canOpenURL(url)
      .then(supported => {
        if (!supported) {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '提示',
            text: '您的设备不支持该功能，请手动拨打',
            okText: '确定',
            isClickBg: false,
          });
          return;
        }
        return Linking.openURL(url);
      }).catch((err) => {
        msg.emit('app:tip', { text: err });
      });
  };

  /**
   * 接口
   */
  // 请求虚拟油卡数据
  getFictitiousCardById = () => {
    const { cardData } = this.state;
    oil.getAuthById({ id: cardData.id }).then(res => {
      if (res.success) {
        this.setState({ cardData: res.data, userType: res.data.type }, () => {
          this.getFictitiousCardQrCode();
        });
      } else {
        msg.emit('app:tip', { text: res.msg || '连接错误' });
        msg.emit('router: back');
      }
    });
  }

  // 获取二维码
  getFictitiousCardQrCode = () => {
    const { cardData } = this.state;
    let apiName = 'qccodeForAgreement';
    if (cardData.id) {
      oil[apiName]({ id: cardData.id }).then(res => {
        if (res.success) {
          const { qccode, no } = res.data;
          this.setState({
            qrCode: qccode,
            pumpOilNo: no
          }, () => {
            this.refreshQrCode();
            this.getVerificationResult();
          });
        }
      });
    }
  }

  // 是否核销成功
  // 接口返回： 0 等待扫码(页面不变化) 继续请求 | 1 扫码核销中 | 2 扫码异常 | 4 支付成功 | 6 余额不足
  getVerificationResult = () => {
    const { pumpOilNo } = this.state;
    oil.getVerificationResult({ pumpOilNo }).then(res => {
      if (res.success) {
        const { status, amount, pumpOilNo, yp } = res.data;
        switch (status) {
        case 0:
          this.pollingResult(this.getVerificationResult);
          break;
        case 1:
          this.setState({ isWriteOff: true });
          this.pollingResult(this.getVerificationResult);
          break;
        case 2:
          this.setUpQrCodeInterval(false);
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '扫码失败',
            text: `${res.data.msg || '请重试'}`,
            okText: '重试',
            isClickBg: false,
            okFn: () => {
              this.setState({ qrCodeCountDown: 59 });
              this.setUpQrCodeInterval(true);
            },
          });
          break;
        case 4:
          this.setUpQrCodeInterval(false);
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '核销成功',
            text: `¥${amount}`,
            okText: '确定',
            isClickBg: false,
            okFn: () => {
              this.setState({ isWriteOff: false });
              msg.emit('router: goToNext', {
                routeName: 'WriteOffDetails',
                pumpOilNo: pumpOilNo,
                backRouteName: 'OilCardPlatform'
              });
            },
          });
          break;
        case 6:
          this.setUpQrCodeInterval(false);
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '账户余额不足',
            text: '您当前油卡账户余额不足。如有疑问，请联系车主或物流公司处理',
            okText: '我知道了',
            isClickBg: false,
            okFn: () => {
              msg.emit('router: back');
            },
          });
          break;
        }
      }
    });
  }

  // 获取客服电话
  getConfigValue = () => {
    AsyncStorage.getItem(cache.SERVICE_NUMBER).then((res) => {
      this.setState({ serviceNumber: res });
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    paddingHorizontal: px2dp(20),
    justifyContent: 'space-between'
  },
  detailsContainer: {
    flex: 1,
    position: 'relative',
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(24),
    marginTop: '25%',
    marginBottom: '40%',
  },
  oilCardContainer: {
    position: 'absolute',
    top: px2dp(-155),
    width: '100%',
    alignItems: 'center',
  },
  detailsDataContainer: {
    flex: 1,
    marginTop: px2dp(155),
    alignItems: 'center',
    borderBottomRightRadius: px2dp(24),
    borderBottomLeftRadius: px2dp(24),
  },
  detailsHeadTitle: {
    height: px2dp(100),
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomWidth: px2dp(1),
    borderBottomColor: '#F0EFEF',
    marginTop: '6%'
  },
  detailsHeadTitleDriverContainer: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    paddingHorizontal: px2dp(24),
    alignItems: 'center',
    width: '100%',
    flex: 1,
  },
  qrCodeContainer: {
    justifyContent: 'center',
    marginVertical: px2dp(20),
    alignItems: 'center',
    flex: 1,
  },
  detailsTipsContainer: {
    position: 'absolute',
    bottom: px2dp(-75),
    height: px2dp(96),
    width: '100%',
    backgroundColor: '#FAFAF9',
    borderBottomRightRadius: px2dp(24),
    borderBottomLeftRadius: px2dp(24),
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  },
  detailsTipsText: {
    flex: 1,
    fontSize: px2dp(28),
    color: '#999793',
    textAlign: 'center'
  },
});
